class UserStoriesController < ApplicationController
  before_filter :productBacklog_allow_show, :only => [:show]
  before_filter :userStory_allow_create, :only => [:new,:create]
  before_filter :userStory_allow_edit, :only => [:edit,:update]
  before_filter :userStory_allow_delete, :only => [:delete]
  before_filter :userStory_allow_accept, :only => []
  
  # muss noch überarbeitet werden, 
  # da UserStoryToSprintBacklog eigentlich dafür sein soll
  before_filter :userStory_allow_rate, :only => [:rate,:addratingtosprintbacklog]
  
  def productBacklog_allow_show
    if current_user# && current_user_role.ProductBacklog == true
      return true
    else
      render :partial => "layouts/denied"
      #redirect_to(:controller => 'sessions', :action => 'new')
      return false
    end
  end
  
  def userStory_allow_create
    if current_user# && current_user_role.UserStoryCreate == true
      return true
    else
      render :partial => "layouts/denied"
      #redirect_to(:controller => 'sessions', :action => 'new')
      return false
    end
  end
  
  def userStory_allow_edit
    if current_user# && current_user_role.UserStoryEdit == true
      return true
    else
      render :partial => "layouts/denied"
      #redirect_to(:controller => 'sessions', :action => 'new')
      return false
    end
  end
  
  def userStory_allow_delete
    if current_user# && current_user_role.UserStoryDelete == true
      return true
    else
      render :partial => "layouts/denied"
      #redirect_to(:controller => 'sessions', :action => 'new')
      return false
    end
  end  
  
  def userStory_allow_accept
    if current_user# && current_user_role.UserStoryAccept == true
      return true
    else
      render :partial => "layouts/denied"
      #redirect_to(:controller => 'sessions', :action => 'new')
      return false
    end
  end  
  
  def userStory_allow_rate
    if current_user# && current_user_role.UserStoryPoker == true
      return true
    else
      render :partial => "layouts/denied"
      #redirect_to(:controller => 'sessions', :action => 'new')
      return false
    end
  end
  
  #private
  def new
    status = :ok
    anzahl_user_stories = UserStory.find_all_by_product_backlog_pid(ProductBacklog.find_by_project_pid(current_user.current_project_id), :conditions => {:user_story_state_pid => [UserStoryState.find_by_status("Offen").id, UserStoryState.find_by_status("Entwurf").id, UserStoryState.find_by_status("Zu&nbsp;pr&uuml;fen").id, UserStoryState.find_by_status("Im&nbsp;Sprintbacklog").id]}).count
    unless anzahl_user_stories < Project.find_by_id(current_user.current_project_id).max_user_stories
      status = :error
    end
    @answers = Array.new Questionnaire.count
    @criterions = Array.new
    @user_story = UserStory.new
    #anzahl.times { @user_story.answers_to_questionnaires.build }
    @user_story.user_pid = current_user.id
    @user_story.product_backlog_pid = ProductBacklog.find_by_project_pid(current_user.current_project_id).id
    @user_story.id = UserStory.last.id+1
    @url = "../product_backlogs/create"

    flash[:error] = []
    
    render :layout => nil, :status => status
  end

  def edit
    flash[:error] = []
    unless(params[:id] == nil)
      @answers = AnswersToQuestionnaire.joins(:user_story).where(:user_story_id => params[:id])
      @criterions = Criterion.joins(:user_story).where(:user_story_id => params[:id])
      @user_story = UserStory.find_by_id(params[:id])
      
      #@user_story[:answers_to_questionnaires_attributes]#['+i.to_s+'][answer]
      #@user_story.product_backlog_pid = Project.find_by_id(ProductBacklog.find_by_id(@user_story.product_backlog_pid).project_pid).name
      @url = "../product_backlogs/update"
      render :layout => nil
    else
      @url = "../product_backlogs/create"
      #params[:user_story][:product_backlog_pid] = Project.find_by_name(params[:user_story][:product_backlog_pid]).id
      @user_story = UserStory.new(params[:user_story])
    end
  end
  
  def update
    @user_story = UserStory.find_by_id(params[:user_story][:id])
    params[:user_story][:product_backlog_pid] = Project.find_by_name(params[:user_story][:product_backlog_pid]).id
    if(@user_story.update_attributes(params[:user_story]))
      redirect_to :controller => "product_backlogs", :action => "show"
    else
      flash[:error] = @user_story.errors
      flash[:notice] = "failure_update"
      flash.keep
      render "product_backlogs/show"
    end unless (@user_story == nil)
  end

  def delete
    @ids = params[:items].split(",")
    @not_deleted = Array.new
    @ids.each do |id|
      @id = UserStory.find_by_id(id)
      if(@id != nil)
        @id.destroy
      else
        @not_deleted.append(id)
      end
    end
    
    if(!@not_deleted.empty?)
      render :json => @not_deleted
    else
      render :text => "0"
    end
  end
  
  def delete_criterion
    @found = 0
    unless params[:id] == "undefined"
      begin
        @criterion = Criterion.find(params[:id])
        @found = 1
        @criterion.destroy
        unless @criterion.destroyed?
          @found = "Akzeptanzkriterium konnte nicht gel&ouml;scht werden! Bitte versuchen Sie es sp&auml;ter erneut!"
        end
      rescue ActiveRecord::RecordNotFound => e
        @found = 0
      end
    end
    
    render :text => @found     
  end
  
  def show
    @sort = "user_story_priority_pid"
    @productBacklog = ProductBacklog.find_or_create_by_project_pid(current_user.current_project_id)
    
    case params[:sort_by]
      when "0"
        @sort = "user_story_priority_pid"
      when "1"
        @sort = "created_at"
      when "2"
        @sort = "updated_at"
      when "3"
        @sort = "user_story_state_pid"
      when "4"
        @sort = "user_story_rating_id DESC"
      when "5"
        @sort = "id"
    end
    
    
    if(params[:state_pid] != nil and params[:state_pid] != "")
      @user_story = UserStory.find_all_by_product_backlog_pid_and_user_story_state_pid(@productBacklog.id, params[:state_pid], :order => @sort)
      #@user_story = UserStory.joins(:product_backlog).where('project_id' => current_user.project_id, 'user_story_state_pid' => params[:state_pid])
    else
      @user_story = UserStory.find_all_by_product_backlog_pid(@productBacklog.id, :order => @sort,  :conditions => {:user_story_state_pid => [UserStoryState.find_by_status("Offen").id, UserStoryState.find_by_status("Entwurf").id, UserStoryState.find_by_status("Zu&nbsp;pr&uuml;fen").id]})
      #@user_story = UserStory.joins(:product_backlog).where('project_id' => current_user.project_id)
    end
    
    render :layout => nil
  end

  def create
    params[:user_story][:product_backlog_pid] = Project.find_by_name(params[:user_story][:product_backlog_pid]).id
    params[:user_story][:user_pid] = current_user.id
    @user_story = UserStory.new(params[:user_story])
    flash.keep(:notice)
    if(@user_story.save)
      flash[:notice] = "success"
      redirect_to :controller => "product_backlogs", :action => "show"#, :notice => "success"
    else
      flash[:notice] = "failure"
      flash[:error] = @user_story.errors
      flash.keep
      render "product_backlogs/show"
    end 
  end
  
  def rate
    @ids = params[:items].split(",")
    @user_stories = Array.new
    
    @ids.each do |id|
      user_story = UserStory.find_by_id(id)
      @user_stories.append(user_story) unless (user_story == nil)
    end
    flash.keep

    render :layout => nil
  end
  
  def addratingtosprintbacklog
    @debug = Hash.new

    params.each_with_index do |param, i|              # params[0] ist die user_story_id
                                                      # params[1] ist die rating_pid
      unless i>params.size-4
        param[0] = param[0].split('[')[1].split(']')[0]
        @user_story = UserStory.find_by_id(param[0])
        if(@user_story == nil)
          @debug[param[0]] = "error"
        else
          if @user_story.update_attributes(:sprint_backlog_id => Project.find_by_id(current_user.current_project_id).sprint_id, :user_story_rating_id => param[1], :user_story_state_pid => UserStoryState.find_by_status("Im&nbsp;Sprintbacklog").id)
            @debug[param[0]] = "rated"
          else
            @debug[param[0]] = "error"
          end
        end
      
      end
    end

    render :layout => false
  end
end
